#!/bin/bash

#############################################################################

#if [ $# -lt 2 ]; then echo "I expect at least two arguments. Please, check calling $0, exit 1";exit 1; fi;

echo "Number of arguments $#";

WORKINGDIR=`pwd`;
echo "Directory is ${WORKINGDIR}"

MAXEVENTS=`grep MaxEvents $RUNTIME_AREA/arguments.xml | awk -F "\"" '{print $2}' | head -1 `
echo "Events = $MAXEVENTS"


if [ ! -f utils.sh ]; then echo "file utils.sh is required, exit"; exit 1; fi;

source utils.sh;

###Check version of utils.sh
#It must contain the command
cmd=`ListOfFilesForCrab | grep "command not found"`;
if [ -n "$cmd" ]; then echo "file utils.sh is too old. Update it, exit";exit 1; fi;

#It must contain the command
cmd=`Changefield | grep "command not found"`;
if [ -n "$cmd" ]; then echo "file utils.sh is wrong. Update it, exit";exit 1; fi;



##Cange some fields in original pset.py

Changefield "input" "cms.untracked.int32" 3 "cms.untracked.int32(${MAXEVENTS})" MC_cfg_genParticles.py MC_cfg_genParticles.py

a=`findLine "number_of_jobs" "=" crab.cfg`; 
num_jobs=`field "$a" 3`;

echo "num_jobs = $num_jobs"

###If we have several job_config_cmsRun_genParticles. It might be due to some bugs. Or we have input "job_config_cmsRun_genParticles_bla_bla" 
###instead of "job_config_cmsRun_genParticles" after multicrab submission.

a=`ls job_config_cmsRun_genParticles*`;
b=`echo $a | tr ' ' '\n' | awk '{if (NR==1) print $0}'`;
if [ "$b" != "job_config_cmsRun_genParticles" ]; then  mv "$b" job_config_cmsRun_genParticles; fi

###Create a list of files

#$1 must number of job
#$2 must firts positional arg from crab.cfg

##Test
echo first argument = $1
echo second argument =$2

#ListOfFilesForCrab  job_config_cmsRun_genParticles  $1 $2
#ListOfFilesForCrab  job_config_cmsRun_genParticles  $NJob $1
#ListOfFilesForCrab  job_config_cmsRun_genParticles  $NJob 30
ListOfFilesForCrab  job_config_cmsRun_genParticles  $1 ${num_jobs}

ls -ld *;

mv job_config_cmsRun_genParticles_$NJob job_config_cmsRun_genParticles

echo "!!!!!!!!!!!!!!!!!!"
echo "!!!!!!!!!!!!!!!!!!"
echo "!!!!!!!!!!!!!!!!!!"

ls -ld *;

#cat pset.py;

echo "NJob = $NJob"

# Generate the Framework Job Report
#cmsRun -j $RUNTIME_AREA/crab_fjr_$NJob.xml -p pset.py
#cmsRun -j $RUNTIME_AREA/crab_fjr_$1.xml -p pset.py
cmsRun -j $RUNTIME_AREA/crab_fjr_$1.xml -p MC_cfg_genParticles.py

echo "Current Directory is `pwd`"
ls -ld *

exit 0

